

workspace_functions = {
    view_save: function(elements) {
        $("body").on("click", elements, function() {

            var form_type = $(this).attr("data-form-type");
            var modal_title = $(this).attr("data-workspace");
            //jDialog(message, value,width, height, top, function(){});
            var save_string = save_workspace(form_type, modal_title);

           var newDialog = new jDialog(save_string, "", "", "", "", function() {});
           newDialog.themeDialog("modal2");
            disableFormSettings()
        });
    },
    preview_form: function(elements) {
        $("body").on("click", elements, function() {
            var form_type = $(this).attr("data-form-type");
            var workspace_width = $(".formbuilder_ws").outerWidth();
            var workspace_height = $(".formbuilder_ws").outerHeight();
            var pathname = window.location.pathname;
            // Get Button
            var btnName = $(".setObject_btn").map(function() {
                return $(this).children().val();
            }).get().join();
            var user_view = $("#user_url_view").val();
            switch (form_type) {
                case "organizational_chart":
                    var workspace_content = $(".orgchart_ws").html();

                    var workspace = {};
                    workspace["WorkspaceHeight"] = workspace_height;
                    workspace["WorkspaceWidth"] = workspace_width;
                    workspace['WorkspaceContent'] = workspace_content;
                    workspace['BtnName'] = btnName;
                    var json_encode = JSON.stringify(workspace);
                    pid = json_encode;
                    workspace_width = parseInt(workspace_width) + 15;
                    //$.post('/preview', {json_encode:json_encode }, function() {
                    // var win = window.open('/workspace?view_type=preview&formWidth=' + workspace_width + '&formHeight=' + workspace_height + '&type=orgchart', '_blank');
                    if (pathname == user_view + "organizational_chart") {
                        var win = window.open(user_view + 'workspace?view_type=preview&formWidth=' + workspace_width + '&formHeight=' + workspace_height + '&type=orgchart', '_blank');
                    } else {
                        var win = window.open('/workspace?view_type=preview&formWidth=' + workspace_width + '&formHeight=' + workspace_height + '&type=orgchart', '_blank');

                    }
                    win.focus();
                    break;

                case "formbuilder":
                    var workspace_content = $(".formbuilder_ws").html();

                    var workspace = {};
                    workspace["WorkspaceHeight"] = workspace_height;
                    workspace["WorkspaceWidth"] = workspace_width;
                    workspace['WorkspaceContent'] = workspace_content;
                    workspace['BtnName'] = btnName;
                    var json_encode = JSON.stringify(workspace);
                    pid = json_encode;
                    
                    // alert(user_view)
                    //$.post('/preview', {json_encode:json_encode }, function() {
                    if (pathname == user_view + "formbuilder") {
                        var win = window.open(user_view + 'workspace?view_type=preview&formWidth=' + workspace_width + '&formHeight=' + workspace_height, '_blank');
                    } else {
                        var win = window.open('/workspace?view_type=preview&formWidth=' + workspace_width + '&formHeight=' + workspace_height, '_blank');

                    }
                    win.focus();

                    //});
                    break;

                case "workflow":
                    var workspace_content = $(".workflow_ws").html();

                    var workspace = {};
                    workspace["WorkspaceHeight"] = workspace_height;
                    workspace["WorkspaceWidth"] = workspace_width;
                    workspace['WorkspaceContent'] = workspace_content;
                    workspace['BtnName'] = btnName;
                    var json_encode = JSON.stringify(workspace);
                    pid = json_encode;
                    workspace_width = parseInt(workspace_width) + 15;
                    //$.post('/preview', {json_encode:json_encode }, function() {
                    // var win = window.open('/workspace?view_type=preview&formWidth=' + workspace_width + '&formHeight=' + workspace_height + '&type=flowchart', '_blank');
                    if (pathname == user_view + "workflow") {
                        var win = window.open(user_view + 'workspace?view_type=preview&formWidth=' + workspace_width + '&formHeight=' + workspace_height + '&type=flowchart', '_blank');
                    } else {
                        var win = window.open('/workspace?view_type=preview&formWidth=' + workspace_width + '&formHeight=' + workspace_height + '&type=flowchart', '_blank');

                    }
                    win.focus();
                    break;
                case "generate":
                    var workspace_content = $(".formbuilder_ws").html();
                    var formID = $("#FormId").val();
                    var requestID = $("#requestID").val();
                    var trackNo = $("#trackNo").val();
                    var workspace = {};
                    workspace["WorkspaceHeight"] = workspace_height;
                    workspace["WorkspaceWidth"] = workspace_width;
                    workspace['WorkspaceContent'] = workspace_content;
                    workspace['WorkspaceFormID'] = formID
                    workspace['WorkspaceRequestID'] = requestID
                    workspace['WorkspaceTrackNo'] = trackNo
                    workspace['BtnName'] = btnName;
                    var json_encode = JSON.stringify(workspace);
                    pid = json_encode;
                    // var win = window.open('/workspace?view_type=preview&formWidth=' + workspace_width + '&formHeight=' + workspace_height + '&formID=' + formID, '_blank');
                    if (pathname == user_view + "generate") {
                        var win = window.open(user_view + 'workspace?view_type=preview&formWidth=' + workspace_width + '&formHeight=' + workspace_height + '&formID=' + formID, '_blank');
                    } else {
                        var win = window.open('/workspace?view_type=preview&formWidth=' + workspace_width + '&formHeight=' + workspace_height + '&formID=' + formID, '_blank');

                    }
                    //$.post('/preview', {json_encode:json_encode }, function() {
                    win.focus();
                    break;
            }
        });
    },
    save_form_workspace: function(elements) {
        $("body").on("click", elements, function() {

            var form_type = $(this).attr("data-form-type");
            // Settings
            var workspace_title = $(".workspace_title").val();
            var workspace_displayName = $(".workspace_displayName").val();
            var workspace_prefix = $(".workspace_prefix").val();
            var workspace_type = $(".workspace_type option:selected").val();
            var workspace_width = $(".form_size_width").val();
            var workspace_height = $(".form_size_height").val();



        });
    }
}

// Open / Close Settings on Workspace
$(function($) {
    $.fn.extend({
        formbuilder: function(options) {

            var settings = {
                type: "open", // Default action for panel settings
                auto_open: "true" // Auto Open

            };

            options = $.extend(settings, options);

            return this.each(function() {
                var o = options;
                var obj = $(this);

                // Open Close Properties   
                if (o.type == "open") {

                    $("body").on("click", ".form_settings_open", function() {
                        // Functions for open panel settings
                        var pos = {
                            pos_top_action: "-212",
                            pos_top_prop_action: "0"
                        }

                        form_settings(this, ".form_properties", ".form_properties_actions", "form_settings_open", "form_settings_close", pos);

                    });
                } else {
                    $("body").on("click", ".form_settings_close", function() {

                        // Functions for close panel settings
                        var pos = {
                            pos_top_action: "0",
                            pos_top_prop_action: "211"
                        }
                        form_settings(this, ".form_properties", ".form_properties_actions", "form_settings_close", "form_settings_open", pos);

                    });
                    //}

                }

            });
        }
    });


});
/*---------------------------------------- Functions for Form Builder ---------------------------------*/

/*
 * Functions for open / close panel
 *
 */

function form_settings(elements, panel, panel_settings, panel_actions_remove, panel_action, pos) {

    $(panel).animate({right: pos.pos_top_action}, "slow");
    $(panel_settings).animate({right: pos.pos_top_prop_action}, "slow");
    $(elements).removeClass(panel_actions_remove);
    $(elements).addClass(panel_action);

}

/*
 * Ruler
 *
 */

function dragShowHorizontalRuler(passedElement, mouseX, mouseY, container) {
    var container_of_passed_ele = $(passedElement).closest(container);
    var doi = $(passedElement).attr("data-object-id");
    if($(passedElement).find(".getFields_"+doi).length==0){
        addMY = $(passedElement).offset().top - (mouseY+1);
    }else{
        addMY = $(passedElement).find(".getFields_"+doi).eq(0).offset().top - (mouseY+1);
        
    }
    if ($(".ws-ruler-horizontal-row-guide").length >= 1) {

        $(".ws-ruler-horizontal-row-guide").css({
            top: /*passedElement.offset().top+1*/(mouseY + addMY) - container_of_passed_ele.offset().top
        });
    } else {

        tempAppendShowRulerHorizontalRowGuide = $('<span class="draggable ui-draggable ws-ruler-horizontal-row-guide"></span>');

        container_of_passed_ele.append(tempAppendShowRulerHorizontalRowGuide);

        tempAppendShowRulerHorizontalRowGuide.css({
            top: /*passedElement.offset().top+1*/(mouseY + addMY) - container_of_passed_ele.offset().top,
            left: 0
        });
    }
    ruler_h_top = $(".ws-ruler-horizontal-row-guide").offset().top - container_of_passed_ele.offset().top;
    if (ruler_h_top != (passedElement.offset().top - container_of_passed_ele.offset().top)) {
        $(".ws-ruler-horizontal-row-guide").css({
            top: /*passedElement.offset().top*/(mouseY + addMY) - container_of_passed_ele.offset().top
        });
    }
}
function dragShowVerticalRuler(passedElement, mouseX, mouseY, container) {
    var container_of_passed_ele = $(passedElement).closest(container);
    // console.log("VERTICAL RULER",passedElement,container_of_passed_ele.attr("data-object-id"))
    var doi = $(passedElement).attr("data-object-id");
    if($(passedElement).find(".getFields_"+doi).length==0){
        addMX = $(passedElement).offset().left - mouseX;
    }else{
        addMX = $(passedElement).find(".getFields_"+doi).eq(0).offset().left - mouseX;
        
    }
    // console.log("WAAARR",addMX)
    container_of_passed_ele = $(passedElement).closest(container);
    if ($(".ws-ruler-vertical-column-guide").length >= 1) {

        $(".ws-ruler-vertical-column-guide").css({
            left: /*passedElement.offset().left*/(mouseX + addMX) - container_of_passed_ele.offset().left
        });
    } else {

        tempAppendShowRulerVerticalColumnGuide = $('<span class="draggable ui-draggable ws-ruler-vertical-column-guide"></span>');

        container_of_passed_ele.append(tempAppendShowRulerVerticalColumnGuide);

        tempAppendShowRulerVerticalColumnGuide.css({
            left: (mouseX + addMX) - (container_of_passed_ele.offset().left + 0 ),
            top: 0
        });
    }
    ruler_v_left = $(".ws-ruler-vertical-column-guide").offset().left - container_of_passed_ele.offset().left;
    if (ruler_v_left != (passedElement.offset().left - container_of_passed_ele.offset().left)) {
        $(".ws-ruler-vertical-column-guide").css({
            left: /*passedElement.offset().left*/(mouseX + addMX ) - (container_of_passed_ele.offset().left + 0)
        });
    }
}
function removeRuler() {
    $(".ws-ruler-horizontal-row-guide").remove();
    $(".ws-ruler-vertical-column-guide").remove();
}



/*
 * Call Save Functions Design
 *      Via Ctrl + S
 *
 */

function control_save_workspace(elements) {
    //handles ctrl-s
    $(document).keydown(function(event) {
        var pathname = window.location.pathname;
        var user_view = $("#user_url_view").val();
        if (pathname.indexOf("organizational_chart") >= 0 || pathname.indexOf("formbuilder") >= 0 || pathname.indexOf("workflow") >= 0 || pathname.indexOf("report") >= 0 || pathname.indexOf("generate") >= 0
                || pathname == user_view + "create_forms") {

            var currKey = 0, e = e || event;
            currKey = e.keyCode || e.which || e.charCode;  //do this handle FF and IE
            if (!(String.fromCharCode(event.which).toLowerCase() == 's' && event.ctrlKey) && !(event.which == 19))
                return true;
            event.preventDefault();

            var form_type = $(elements).attr("data-form-type");
            var modal_title = $(elements).attr("data-workspace");

            if (!modal_title) {
                return;
            }

            /* Save Functions Design */
            var save_string = save_workspace(form_type, modal_title);
            //jDialog(message, value,width, height, top, function(){});
          var newDialog = new  jDialog(save_string, "", "", "", "", function() {
            });

          newDialog.themeDialog("modal2");

            disableFormSettings()
            return false;
        }

    });
}


/*
 * Save Functions Design
 *      Containing (Organizational Chart, Formbuilder, Workflow);
 *      @form_type = validation of save functions details
 *      @modal_title = set the title of save properties modal
 *
 */

function save_workspace(form_type, modal_title) {
    var json = $("body").data();
    var user_view = $("#user_url_view").val();

   
    var ret = '';
    var disabled = "";
    var pathname = window.location.pathname;
    if (pathname == "/generate" || pathname != user_view + "formbuilder") {
        disabled = "disabled=disabled";
    }
    if (pathname == user_view + "organizational_chart" || pathname == "/organizational_chart") {
        disabled = "";
    }
    if (pathname == user_view + "workflow" || pathname == "/workflow") {
        disabled = "";
    }
    if (pathname == "/formbuilder") {
        disabled = "";
    }
    if (pathname == user_view + "report" || pathname == "/report") {
        disabled = "";
    }
    if (pathname == user_view + "generate" || pathname == "/generate") {
        disabled = "disabled=disabled";
    }
    ret += '<h3 class="fl-margin-bottom">';
    ret += '<i class="icon-save"></i> ' + modal_title;
    ret += '</h3>';
    ret += '<div class="hr"></div>';
    ret += '<div class="fields">';
    ret += '<div class="label_below2"> Details: </div>';
    if (form_type == "formbuilder") {
        var form_id = $("#FormId").val();
        var form_logo = $("body").data("form_logo");
        var logo = '/images/formLogo/' + MD5(MD5(form_id)) + '/small.png';
        ret += '<center><img data-placement="bottom" data-original-title="" src="' + logo + '" width="30" height="30" class="avatar userAvatar form_logo"></center>';
    }
    //    if (form_type=="formbuilder") {
    //    ret += '<div class="input_position" style="text-align:center;">';
    //	ret += '<img data-original-title="" src="http://eforms.gs3.com.ph:80/images/avatar/small.png" width="44" height="44" class="avatar userAvatar">';
    //    ret += '</div>';
    //    }
    ret += '</div>';

    ret += '<div class="fields">';
    ret += '<div class="label_below2"> Title:<font color="red">*</font> </div>';
    ret += '<div class="input_position">';
    if (pathname == user_view + "generate" || pathname == "/generate") {
         // For Generate Report
        var form_name = $(".form-workspace-form-name").html();
        ret += '<input type="text" name="workspace_title" ' + disabled + ' id="workspace_title" class="workspace_title form-text fl-margin-bottom" style="margin-top:5px;" value="' + form_name + '">';
    }else{
        ret += '<input type="text" name="workspace_title" ' + disabled + ' id="workspace_title" class="workspace_title form-text fl-margin-bottom" style="margin-top:5px;" value="' + if_undefinded(json.workspace_title, "") + '">';
    }
    ret += '</div>';
    ret += '</div>';

    // For Organizatioanl Chart And Workflow Description
    if (form_type != "formbuilder") {
        ret += '<div class="fields">';
        ret += '<div class="label_below2"> Description: </div>';
        ret += '<div class="input_position">';
        ret += '<textarea class="form-textarea_save workspace_description fl-margin-bottom" name="workspace_description" id="workspace_description" style="resize:none"></textarea>';
        ret += '</div>';
        ret += '</div>';
    }

    if (form_type == "formbuilder" || form_type == "generate") {

        /*
         * Workspace formbuilder
         */

        ret += '<div class="fields">';
        ret += '<div class="label_below2"> Display Name:<font color="red">*</font> </div>';
        ret += '<div class="input_position">';
        if (pathname == user_view + "generate" || pathname == "/generate") {
         // For Generate Report
            var form_name = $(".form-workspace-form-name").html();
            ret += '<input type="text" name="workspace_displayName" id="workspace_displayName" class="fl-margin-bottom workspace_displayName form-text class" style="margin-top:5px;" value="' + form_name + '">';
        }else{
            ret += '<input type="text" name="workspace_displayName" id="workspace_displayName" class="fl-margin-bottom workspace_displayName form-text class" style="margin-top:5px;" value="' + if_undefinded(json.workspace_displayName, "") + '">';
        }
        ret += '</div>';
        ret += '</div>';

        if (form_type != "generate") {
            ret += '<div class="fields">';
            ret += '<div class="label_below2"> Form Category: </div>';
            ret += '<div class="input_position">';
            ret += '<select class="form-select form_category fl-margin-bottom" name="form_category" id="form_category" style="margin-top:5px; margin-bottom:5px;">';
            ret += getFormCategory();
            ret += '</select>';
            ret += '</div>';
            ret += '</div>';
            ret += '<div class="fields">';
            ret += '<div class="label_below2"> Form Logo: </div>';
            ret += '<div class="input_position">';
            ret += '<form action="/ajax/uploadFile" method="POST" class="formLogo" id="formLogo" enctype="multipart/form-data">';
            ret += '<div id="uniform-fileInput" class="uploader fl-margin-bottom" style="margin-top:5px;">';
            ret += '<input type="file" data-action-id="2" value="upload" name="uploadLogoForm" id="uploadLogoForm" size="24" data-action-type="uploadLogoForm" style="opacity: 0;" class="upfile">';
            ret += '<span id="uploadFilename_2" class="filename">No file selected</span>';
            ret += '<span class="action">Choose File</span>';
            ret += '<input type="hidden" value="postLogoUpload" name="uploadType">';
            ret += '</div>';
            ret += '</form>';
            ret += '<img src="/images/loader/load.gif" class="postLogoLoader display" style="margin-top: 13px;margin-left: 5px;">';
            ret += '</div>';
            ret += '</div>';
            ret += '<div class="fields">';
            ret += '<div class="label"> Reference Format:</div>';
            ret += '</div>';
            ret += '<div class="fields">';
            ret += '<div class="label_below2"> Prefix:<font color="red">*</font>  </div>';
            ret += '<div class="input_position">';
            ret += '<input type="text" name="workspace_prefix" value="' + if_undefinded(json.workspace_prefix, "") + '" id="workspace_prefix" class="workspace_prefix form-text fl-margin-bottom" style="margin-top:5px;">';
            ret += '</div>';
            ret += '</div>';
            ret += '<div class="fields">';
            ret += '<div class="label_below2"> Type:<font color="red">*</font> </div>';
            ret += '<div class="input_position">';
            ret += '<select class="form-select workspace_type fl-margin-bottom" name="workspace_type" id="workspace_type" style="margin-top:5px;">';
            ret += '<option value="0">----------------------------Select----------------------------</option>';
            ret += '<option ' + setSelected("Sequential", if_undefinded(json.workspace_type, "")) + '>Sequential</option>';
            ret += '<option ' + setSelected("DateTime", if_undefinded(json.workspace_type, "")) + '>DateTime</option>';
            ret += '</select>';
            ret += '</div>';
            ret += '</div>';
        }

        //ret += '<input type="text" name="" id="" class=" form-text" style="margin-top:5px;">';
        ret += '</div>';
        ret += '</div>';
    } else {
        if (form_type == "organizational_chart") {
            /*
             * Workspace Organizational Chart
             */
            ret += '<div class="fields">';
            ret += '<div class="label_below2"> Status: <font color="red">*</font></div>';
            ret += '<div class="input_position fl-margin-bottom">';
            ret += '<select class="form-text workspace_status" name="workspace_status" id="workspace_status" style="margin-top:5px;">';
            ret += '<option value="null">----------------------------Select----------------------------</option>';
            ret += '<option value="1">Activate</option>';
            ret += '<option value="0">Deactivate</option>';
            ret += '</select>';
            ret += '</div>';
            ret += '</div>';
        }
    }

    /*
     * Modal Action Button
     * Save / Cancel
     *
     */

    ret += '<div class="fields">';
    ret += '<div class="label_below2"></div>';
    ret += '<div class="input_position" style="margin-top:5px;text-align:right;">';
    ret += '<img src="/images/loader/load.gif" class="display saveFormLoad" style="margin-right:5px;margin-top:2px;"/>';
    ret += '<input type="button" class="btn-blueBtn fl-margin-right save_form_workspace" data-form-type="' + form_type + '" id="save_form_workspace" value="Save">     ';
    ret += '<input type="button" class="btn-basicBtn" id="popup_cancel" value="Cancel">';
    ret += '</div>';
    ret += '</div>';
    
    brokenImage(); // Change broken image into white image
    return ret;
}
function disableFormSettings() {
    // var pathname = window.location;
    // if(getParametersName("view_type",pathname)=="edit"){
    // 	$("#workspace_title").attr("disabled","disabled");
    // 	$("#workspace_displayName").attr("disabled","disabled");
    // 	$("#workspace_prefix").attr("disabled","disabled");
    // 	$("#workspace_type").attr("disabled","disabled");
    // }
}

function getFormCategory() {
    var json = $("body").data();
    // console.log(json)
    var ret = ""
    ret += '<option value="0">----------------------------Select----------------------------</option>';
    $.ajax({
        type: "POST",
        url: "/ajax/formbuilder",
        data: {action: "getCategory"},
        // dataType: "json",
        success: function(data) {
			
            if(data && data!="null"){
                data = JSON.parse(data);
                $.each(data, function(id, val) {
                    ret += '<option value="' + data[id].category_id + '" ' + setSelected(json['form_category'], data[id].category_id) + '>' + data[id].category_name + '</option>';
                });
            }
			$(".form_category").append(ret);
        }
    });
}

RequestPivacy = {
    "authors": function() {
        //alert("authors")
        var newDialog = new jDialog(this.setDialog("Form Authors", "form-authors", "", "fa fa-pencil-square", "faiconColor"), "", "600", "", "", function() {
        });
        newDialog.themeDialog("modal2");
        this.otherAttributes();
    },
    "users" : function(){
        var newDialog = new jDialog(this.setDialog("Form Users", "form-users", "", "fa fa-pencil-square", "faiconColor"), "", "600", "", "", function() {
        });
        newDialog.themeDialog("modal2");
        this.otherAttributes();
    },
    "readers": function() {
        //alert("readers")
        var note = "Note: Requestor and Current Approver can automatically view the request.";
        var newDialog = new jDialog(this.setDialog("Request Viewer", "form-readers", note, "fa fa-folder-open", "faiconColor"), "", "600", "", "", function() {
        });
         newDialog.themeDialog("modal2");
        this.otherAttributes();
    },
    "admin": function() {
        var newDialog = new jDialog(this.setDialog("Form Admin", "form-admin", "", "fa fa-user", "faiconColor"), "", "600", "", "", function() {
        });
        newDialog.themeDialog("modal2");
        this.otherAttributes();
    },
    "customizedPrint": function() {
        var newDialog = new jDialog(this.setDialog("Customized Print Author", "customized-print", "", "fa fa-print", "faiconColor"), "", "600", "", "", function() {
        });
        newDialog.themeDialog("modal2");
        this.otherAttributes();
    },
    "otherAttributes": function() {
        this.setCheckAllChecked(".fp-user");
        this.bindOnClickCheckBox();
        limitText(".limit-text-ws", 20);
        $(".tip").tooltip();
        $('#content-dialog-scroll').perfectScrollbar();
    },
    "setDialog": function(title, type, note, icon, faiconColor) {
        var self = this;
        var json = $("body").data();
        var formPrivacy = if_undefinded(json['' + type + ''], "");
        var departments_arr;
        var positions_arr;
        var users_arr;
        if (formPrivacy) {
            departments_arr = formPrivacy['departments'];
            positions_arr = formPrivacy['positions'];
            users_arr = formPrivacy['users'];
        }
        var departments = $(".departments").text();
        var positions = $(".positions").text();
        var users = $(".users").text();
        var ret = '<h3 class="fl-margin-bottom">';
        ret += '<i class=" '+ icon +' '+ faiconColor +' icon-save"></i> ' + title;
        ret += '</h3>';
        ret += '<div class="hr"></div>';
        ret += '<div style="margin-top:-5px;font-size:11px;color:red">' + note + '</div>';
        ret += '<div id="content-dialog-scroll" style="position: relative; margin: 0px auto; padding: 0px; width: 100%; height: 300px;overflow: hidden;" class="ps-container">';

        ret += '<div class="content-dialog" style="height: auto;">';

        ret += '<div class="fp-container" style="height: 265px;">';
        ret += '<div class="input_position" style="width:100%">';
        ret += '<div style="margin-top: 10px;">';
        ret += '<label><input type="checkbox" class="fp-allUsers css-checkbox" value="All Users" id="Allusers"/><label for="Allusers" class="css-label"></label> All Users</label> <br />';
        ret += '<div style="margin-left: 20px;">';

        if (type != "form-admin") {
            // for department
            ret += '<div class="container-formUser">';
            ret += '<div class="formUser" rel="getDepartmentFF" ><label class="icon-minus fa fa-minus"></label> <label class="font-bold">Department</label></div>';
            ret += '<div class="getDepartmentFF" style="display:inline-block;width:100%;margin-left:10px;margin-top:5px;">';

            var ctr_dept = 0;
            if (departments) {
                departments = JSON.parse(departments);
                $.each(departments, function(key, val) {
                    ret += '<div style="width:30%;float:left;margin-bottom:2px"> ';
                    //setCheckedArray(value, arr)
                    ret += '<label class="tip" title="' + val.department + '"><input type="checkbox" class="fp-user departments css-checkbox" ' + self.setCheckedArray(val.id, departments_arr) + ' value="' + val.id + '" id="' + val.id + '"/><label for="' + val.id + '" class="css-label"></label> <span class="limit-text-ws">' + val.department + '</span></label>';
                    ret += '</div>';
                    ctr_dept++
                })
            }
            if (ctr_dept == 0) {
                ret += '<span style="color:red">No Department</span>';
            }
            ret += '</div>';
            ret += '</div>';
            // for position
            ret += '<div class="container-formUser">';
            ret += '<div class="formUser" rel="getPositionFF" ><label class="icon-minus fa fa-minus"></label> <label class="font-bold">Position</label></div>';
            ret += '<div class="getPositionFF" style="display:inline-block;width:100%;margin-left:10px;margin-top:5px;">';

            var ctr_pos = 0;
            if (positions) {
                positions = JSON.parse(positions);
                $.each(positions, function(key, val) {
                    if (val.position != "") {
                        ret += '<div style="width:30%;float:left;margin-bottom:2px"> ';
                        ret += '<label class="tip" title="' + val.position + '"><input type="checkbox" class="fp-user positions css-checkbox" ' + self.setCheckedArray(val.position, positions_arr) + ' value="' + val.position + '" id="' + val.position + '"/><label for="' + val.position + '" class="css-label"></label> <span class="limit-text-ws">' + val.position + '</span></label>';
                        ret += '</div>';
                        ctr_pos++;
                    }
                })

            }
            if (ctr_pos == 0) {
                ret += '<span style="color:red">No Positions</span>';
            }
            ret += '</div>';
            ret += '</div>';
        } else {
            users = $(".users-admin").text();
        }

        //for users
        ret += '<div class="container-formUser">';
        ret += '<div class="formUser" rel="getUsersFF" ><label class=" icon-minus fa fa-minus"></label> <label class="font-bold">Users</label></div>';
        ret += '<div class="getUsersFF" style="display:inline-block;width:100%;margin-left:10px;margin-top:5px;">';

        var ctr_usr = 0
        if (users) {
            users = JSON.parse(users);
            $.each(users, function(key, val) {
                ret += '<div style="width:30%;float:left; padding:2px;"> ';
                ret += '<label class="tip" title="' + val.first_name + ' ' + val.last_name + '"><input type="checkbox" class="fp-user users css-checkbox" ' + self.setCheckedArray(val.id, users_arr) + ' value="' + val.id + '" id="users_' + val.id + '"/><label for="users_' + val.id + '" class="css-label"></label> <span class="limit-text-ws">' + val.first_name + ' ' + val.last_name + '</span></label>';
                ret += '</div>';
                ctr_usr++
            })

        }
        if (ctr_usr == 0) {
            ret += '<span style="color:red">No Users</span>';
        }
        ret += '</div>';
        ret += '</div>';
        ret += '</div>';
        ret += '</div>';
        ret += '</div>';
        ret += '</div>';
        ret += '</div>';
        ret += '</div>';
        ret += '<div class="fields">';

        ret += '<div class="label_basic"></div>';
        ret += '<div class="input_position" style="margin-top:5px;text-align:right;">';
        ret += '<input type="button" class="btn-blueBtn fl-margin-right save_form_privacy" data-type="' + type + '" value="Save">     ';
        ret += '<input type="button" class="btn-basicBtn" id="popup_cancel" value="Cancel">';
        ret += '</div>';
        ret += '</div>';
        return ret;
    },
    saveFormPrivacy: function(obj) {
        var data_type = $(obj).attr("data-type");
        var json = $("body").data();
        var json_privacy = {};
        var departments = new Array();
        var positions = new Array();
        var users = new Array();

        //for deoartments
        $(".departments").each(function() {
            if ($(this).prop("checked")) {
                departments.push($(this).val());
            }
        })
        //for positions
        $(".positions").each(function() {
            if ($(this).prop("checked")) {
                positions.push($(this).val());
            }
        })
        //for users
        $(".users").each(function() {
            if ($(this).prop("checked")) {
                users.push($(this).val());
            }
        })

        //
        json_privacy['departments'] = departments;
        json_privacy['positions'] = positions;
        json_privacy['users'] = users;
        //
        json['' + data_type + ''] = json_privacy;

        //close the window
        //$("#popup_cancel").click();
        $('.fl-closeDialog').click();

    },
    "checkAllUsers": function(obj) {
        if ($(obj).prop("checked")) {
            $(obj).closest(".fp-container").find(".fp-user").prop("checked", true);
        } else {
            $(obj).closest(".fp-container").find(".fp-user").prop("checked", false);
        }
    },
    "setCheckedArray": function(value, arr) {
        // if(value.indexOf(arr)>=0){
        // 	return "checked='checked'";
        // }
        for (var i in arr) {
            if (value == arr[i]) {
                return "checked='checked'";
                break;
            }
        }
    },
    "defaultChecked": function() {
        var json = $("body").data();
        var json_privacy = {};
        var json_privacy_admin = {};
        var departments_arr = new Array();
        var positions_arr = new Array();
        var users_arr = new Array();
        var users_arr_admin = new Array();

        var departments = $(".departments").text();
        if (departments) {
            departments = JSON.parse(departments);
            $.each(departments, function(key, val) {
                departments_arr.push(val.id);
            })
        }
        //for positions
        var positions = $(".positions").text();
        if (positions) {
            positions = JSON.parse(positions);
            $.each(positions, function(key, val) {
                positions_arr.push(val.position);
            })
        }
        //for users
        var users = $(".users").text();
        if (users) {
            users = JSON.parse(users);
            $.each(users, function(key, val) {
                users_arr.push(val.id);
            })
        }

        var users_admin = $(".users-admin").text();
        if (users_admin) {
            users_admin = JSON.parse(users_admin);
            $.each(users_admin, function(key, val) {
                users_arr_admin.push(val.id);
            })
        }
        //
        json_privacy['departments'] = departments_arr;
        json_privacy['positions'] = positions_arr;
        json_privacy['users'] = users_arr;
		json_privacy_admin['departments'] = "";
		json_privacy_admin['positions'] = "";
        json_privacy_admin['users'] = users_arr_admin;
        //
        json['form-authors'] = json_privacy;
        json['form-admin'] = json_privacy_admin;
    },
    setCheckAllChecked: function(clickedEle) {
        dialogContainer = $(clickedEle).closest(".fp-container");
        totalCheckBox = dialogContainer.find(".fp-user").length;
        totalCheckBoxChecked = dialogContainer.find(".fp-user:checked").length;
        if (totalCheckBox == totalCheckBoxChecked) {
            dialogContainer.find(".fp-allUsers").attr("checked", true);
        } else {
            dialogContainer.find(".fp-allUsers").attr("checked", false);
        }
    },
    bindOnClickCheckBox: function() {
        self = this;
        dialogContainer = $("#popup_container");
        dialogContainer.find(".fp-user").on({
            "click": function(ee) {
                self.setCheckAllChecked(this);
            }
        })
    }
}

$(document).ready(function() {
    //$(".form_settings_open").formbuilder({auto_open:"true"});
    $(".form_settings_open").formbuilder({type: "open"}).formbuilder({type: "close"});


    //check all fields(enabled,hidden,required)
    $("body").on("click", ".checkAllFields", function() {
        CheckProperties.checkAll(this, ".container-fields");
    })



    //set form authors

    $(".form-authors").click(function() {
        RequestPivacy.authors();
    })

    //set form readers

    // $(".form-readers").click(function(){
    // 	RequestPivacy.readers();
    // })
    $("body").on("click", ".form-readers", function() {
        RequestPivacy.readers();
    })
    $("body").on("click", ".form-users", function() {
        RequestPivacy.users();
    })
    $("body").on("click", ".form-admin", function() {
        RequestPivacy.admin();
    })
    $("body").on("click", ".form-customized", function() {
        // alert(123123)
        RequestPivacy.customizedPrint();
    })
    //check all
    $("body").on("click", ".fp-allUsers", function() {
        RequestPivacy.checkAllUsers(this);
    })

    $("body").on("click", ".save_form_privacy", function() {
        RequestPivacy.saveFormPrivacy(this);
    })

    FieldSequence.init();
})


CheckProperties = {
    checkAll: function(obj, container) {
        var self = $(obj);
        if (self.prop("checked") == true) {
            self.closest(container).find("[type='checkbox']").prop("checked", true);
        } else {
            self.closest(container).find("[type='checkbox']").prop("checked", false);
        }
    },
    setCheckAllChecked: function(obj, container, checkAll) {
        dialogContainer = $(container);
        totalCheckBox = dialogContainer.find(obj).length;
        totalCheckBoxChecked = dialogContainer.find(obj + ":checked").length;
        console.log(totalCheckBox + " " + totalCheckBoxChecked);
        if (totalCheckBox == totalCheckBoxChecked) {
            dialogContainer.find(checkAll).attr("checked", true);
        } else {
            dialogContainer.find(checkAll).attr("checked", false);
        }
    },
    bindOnClickCheckBox: function(obj, dialogContainer, checkAll) {
        self = this;
        $(dialogContainer).find(obj).on({
            "click": function(ee) {
                var obj = "." + $(this).attr("class").split(" ")[0];
                self.setCheckAllChecked(obj, dialogContainer, checkAll);
            }
        })
    }
}

function hasScrollLeft(selector){
    {//version 1 getting has scroll
        // var dis_ele = $(selector);
        // var totalScrollWidth = dis_ele.get(0).scrollWidth;
        // var dis_ele_width = dis_ele.outerWidth();
        // if( dis_ele_width >= totalScrollWidth ){
        //  //
        // }else{
        //  //has scroll
        // }
    }

    {//version 2 getting has scroll
        var dis_ele = $(selector);
        var sLeft = dis_ele.scrollLeft();
        var parents_displayed_none = $();
        
        if(dis_ele.is(":visible") == false){
            parents_displayed_none = dis_ele.parents().filter(function(index, element){
                if($(element).css("display") == "none"){
                    return true;
                }else{
                    return false;
                }
            });
            parents_displayed_none.each(function(){
                $(this).css("display","block");
            })
        }
        

        if(sLeft == 0){
            dis_ele.scrollLeft(1);
        }
        if(dis_ele.scrollLeft() >= 1){
            parents_displayed_none.each(function(){
                $(this).css("display","none");
            })
            //has scroll
            return true
        }else if(dis_ele.scrollLeft() <= 0){
            parents_displayed_none.each(function(){
                $(this).css("display","none");
            })
            //no scroll
            return false;
        }
    }
}

function hasScrollTop(selector){
    {//version 1 getting has scroll
        // var dis_ele = $(selector);
        // var totalScrollWidth = dis_ele.get(0).scrollWidth;
        // var dis_ele_width = dis_ele.outerWidth();
        // if( dis_ele_width >= totalScrollWidth ){
        //  //
        // }else{
        //  //has scroll
        // }
    }

    {//version 2 getting has scroll
        var dis_ele = $(selector);
        var sTop = dis_ele.scrollTop();
        var parents_displayed_none = $();
        
        if(dis_ele.is(":visible") == false){
            parents_displayed_none = dis_ele.parents().filter(function(index, element){
                if($(element).css("display") == "none"){
                    return true;
                }else{
                    return false;
                }
            });
            parents_displayed_none.each(function(){
                $(this).css("display","block");
            })
        }

        if(sTop == 0){
            dis_ele.scrollTop(1);
        }
        if(dis_ele.is(":visible")){
            if(dis_ele.scrollTop() >= 1){
                parents_displayed_none.each(function(){
                    $(this).css("display","none");
                })
                //has scroll
                return true
            }else if(dis_ele.scrollTop() <= 0){
                parents_displayed_none.each(function(){
                    $(this).css("display","none");
                })
                //no scroll
                return false;
            }
        }else{
            dis_ele
        }
        
    }
}

FieldSequence = {
    "init" : function(){
        this.createModal();
        this.saveSequence();
    },
    "createModal" : function(){
        $("body").on("click",".field-process-sequence",function(){
            var temp_saved_seq_field_array = $('body').data('saved_seq_field_array');
            var hasMiddleware = 0;
            var ret = '<h3><i class="icon-comment"></i> Middleware Process Sequence</h3>';
            ret += '<div class="hr"></div>';
            ret += '</div>';
            ret += '<div id="content-dialog-scroll" style="position: relative; margin: 0px auto; padding: 0px; width: 100%; height: 300px;overflow: hidden;" class="ps-container">';
            ret += '<div class="content-dialog" style="height: auto;margin-bottom:0x">';
            ret += '<ul class="sequence-sort">';
            
                if(temp_saved_seq_field_array){
                    var temp_fname = "";
                    var temp_ele_field = null;
                    for(var keyin in temp_saved_seq_field_array){
                        temp_fname = temp_saved_seq_field_array[keyin];
                        temp_ele_field = $('[name="'+temp_fname+'"]');
                        if(temp_ele_field.length >= 1){
                            if(temp_ele_field.attr("default-type") == "middleware"){
                                ret += '<li><div class="sequence-field" style="width:100%;height:20px;background-color: #CCC;cursor:move;margin-bottom:2px;font-size: 15px;padding: 5px;" field-name="'+ temp_ele_field.attr("name") +'">'+ temp_ele_field.parents(".setObject").eq(0).find(".obj_label").eq(0).text() +' ('+temp_ele_field.attr("name")+')</div></li>';
                            }
                        }
                    }
                }

                $(".setObject").each(function(eqi_setObj) {
                    if (
                            $(this).attr("data-type") == "labelOnly" ||
                            $(this).attr("data-type") == "createLine" ||
                            $(this).attr("data-type") == "table" ||
                            $(this).attr("data-type") == "tab-panel" ||
                            $(this).attr("data-type") == "listNames"
                            ) {
                        return true; //preventing to insert it to the database
                    }
                    counted_id = $(this).attr("data-object-id");
                    if ($(this).find(".getFields_" + counted_id).attr("name") && $(this).find(".getFields_" + counted_id).attr("default-type") == "middleware") {
                        hasMiddleware++;
                        if(temp_saved_seq_field_array){
                            if(temp_saved_seq_field_array.indexOf( $(this).find(".getFields_" + counted_id).attr("name") ) >= 0){
                                return true;
                            }
                        }
                        ret += '<li><div class="sequence-field" style="width:100%;height:20px;background-color: #CCC;cursor:move;margin-bottom:2px;font-size: 15px;padding: 5px;" field-name="'+ $(this).find(".getFields_" + counted_id).attr("name") +'">'+ $(this).find(".obj_label").eq(0).text() +' ('+$(this).find(".getFields_" + counted_id).attr("name")+')</div></li>';
                    }
                });
            ret += '</ul>';

            ret += '</div>';
            ret += '</div>';
            ret += '<div class="fields" style="border-top:1px solid #ddd;">';
            ret += '<div class="label_basic"></div>';
            ret += '<div class="input_position" style="margin-top:5px;text-align:right;">';
            ret += ' <input type="button" class="btn-basicBtn saveSequence" value="Save">';
            ret += ' <input type="button" class="btn-basicBtn" id="popup_cancel" value="Close">';
            ret += '</div>';
            ret += '</div>';

            if(hasMiddleware>=2){
                var newDialog = new jDialog(ret, "", "", "", "", function() {});
                newDialog.themeDialog("modal2");
                $(".sequence-sort").sortable({
                    "axis":"y",
                });
                $("#content-dialog-scroll").perfectScrollbar();
            }else{
                showNotification({
                    message: "Not enough middleware fields",
                    type: "error",
                    autoClose: true,
                    duration: 3
                });
            }
        })
    },
    "saveSequence" : function(){
        $("body").on("click",".saveSequence",function(){
            var fieldArray = [];
            $(".sequence-field").each(function(){
                fieldArray.push($(this).attr("field-name"));
            })
            console.log(fieldArray)

            // $('.field-process-sequence').data("saved_seq_field_array",fieldArray);
            $('body').data("saved_seq_field_array",fieldArray);
            $(".fl-closeDialog").click();
        })
    },
    "restoreSequence":function(){

    }
}